package com.cheetah.start.common.xss;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
@WebFilter
public class XssSupport implements Filter {

    private static boolean IS_INCLUDE_RICH_TEXT = false;

    @Value("${xss.exclude}")
    private String exclude;
    public List<String> excludes = new ArrayList<>();

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
//        if(log.isDebugEnabled()){
//            log.debug("xss filter is open");
//        }
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        if (handleExcludeURL(req, resp)) {
            filterChain.doFilter(request, response);
            return;
        }
        XssRequest xssRequest = new XssRequest((HttpServletRequest) request, IS_INCLUDE_RICH_TEXT);
        filterChain.doFilter(xssRequest, response);
    }

    private boolean handleExcludeURL(HttpServletRequest request, HttpServletResponse response) {
        if (StrUtil.isNotBlank(exclude)) {
            String[] split = exclude.split(",");
            excludes.addAll(Arrays.asList(split));
        }
        if (excludes == null || excludes.isEmpty()) {
            return false;
        }
        String url = request.getServletPath();
        String[] exclusionsUrls = {".js", ".gif", ".jpg", ".png", ".css", ".ico", ".json", ".yml", ".svg", ".svg", ".eot", ".ttf", ".woff", ".woff2", ".html"};
        for (String str : exclusionsUrls) {
            if (url.contains(str)) {
                log.debug(":[{}]接口已放行xss过滤", url);
                return true;
            }
        }
        try {
            for (String pattern : excludes) {
                Pattern p = Pattern.compile("^" + pattern);
                Matcher m = p.matcher(url);
                if (m.find()) {
                    log.debug(":[{}]接口已放行xss过滤", url);
                    return true;
                }
            }
        } catch (Exception e) {
            log.error("xss异常:[{}]", e.getMessage());
            e.printStackTrace();
        }
        log.debug(":[{}]接口已执行xss过滤", url);
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
//        if(log.isDebugEnabled()){
//            log.debug("xss filter init~~~~~~~~~~~~");
//        }
        String isIncludeRichText = filterConfig.getInitParameter("isIncludeRichText");
        if (StrUtil.isNotBlank(isIncludeRichText)) {
            IS_INCLUDE_RICH_TEXT = BooleanUtil.toBoolean(isIncludeRichText);
        }
        String temp = filterConfig.getInitParameter("excludes");
        if (temp != null) {
            String[] url = temp.split(",");
            for (int i = 0; url != null && i < url.length; i++) {
                excludes.add(url[i]);
            }
        }
    }

    @Override
    public void destroy() {
        log.debug("xss filter destroy~~~~~~~~~~~~");
    }
}
